package com.accounting.client.frontend.system;

import com.accounting.client.ApplicationContext;
import com.accounting.client.remote.obj.Setting;
import com.accounting.client.remote.obj.SettingKey;

import corelib.client.MathUtil;
import corelib.client.NumberFormats;
import corelib.client.Util;
import corelib.client.ui.widget.form.ReadOnlyWidget;
import corelib.client.ui.widget.form.fomatters.ValueFormatter;

public class ReadOnlyCurrencyField {
	
	private ReadOnlyWidget<Double> audField;
	private ReadOnlyWidget<Double> rmbField;
	
	public ReadOnlyCurrencyField() {
		init();
	}

	public ReadOnlyWidget<Double> getAUDField() {
		return this.audField;
	}

	public ReadOnlyWidget<Double> getRMBField() {
		return this.rmbField;
	}
	
	public void setAUD(double value, double rate){
		this.audField.setValue(value);
		this.rmbField.setValue(value * rate);
	}
	
	public void setRMB(double value, double rate) {
		this.rmbField.setValue(value);
		this.audField.setValue(MathUtil.round(value / rate, 2));
	}
	
	public void setAUD(double value){
		Setting setting = ApplicationContext.getSetting(SettingKey.RealRate.getName());
		double rate = Util.getDouble(setting.getValue(), 6.0);
		setAUD(value,rate);
	}
	
	public void setRMB(double value) {
		Setting setting = ApplicationContext.getSetting(SettingKey.RealRate.getName());
		double rate = Util.getDouble(setting.getValue(), 6.0);
		setRMB(value,rate);
	}
	
	private void init() {
		this.audField = ReadOnlyWidget.createCurrencyField();
		this.rmbField = ReadOnlyWidget.createCurrencyField();
		this.audField.setFormatter(new ValueFormatter<Double>(){
			@Override
			public String format(Double value) {
				return NumberFormats.AUD.format(value);
			}
		});
		this.rmbField.setFormatter(new ValueFormatter<Double>(){
			@Override
			public String format(Double value) {
				return NumberFormats.RMB.format(value);
			}
		});
	}
	
	public static ReadOnlyCurrencyField create() { 
		return new ReadOnlyCurrencyField(); 
	}
	
}
